package com.qyhl.webtv.basiclib.base;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.os.IBinder;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.android.arouter.launcher.ARouter;
import com.gyf.immersionbar.ImmersionBar;
import com.orhanobut.hawk.Hawk;
import com.qyhl.webtv.basiclib.R;
import com.qyhl.webtv.basiclib.common.MyObserver;
import com.qyhl.webtv.basiclib.utils.ContextUtilts;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.ToastUtils;
import com.qyhl.webtv.basiclib.utils.dialog.LoadingDialog;
import com.weavey.loading.lib.LoadingLayout;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import es.dmoral.toasty.Toasty;

/**
 * 基础Activity
 *
 * @author
 * @date 2019年3月1日11:18:31
 */
public abstract class BaseActivity extends AppCompatActivity implements View.OnLayoutChangeListener {
    private BaseIViewPresenter mPresenter;
    private ImmersionBar mImmersionBar;
    private LoadingDialog.Builder mBuilder;

    //屏幕高度
    public int screenHeight = 0;
    public static final int ERROR = 1;
    public static final int INFO = 2;
    public static final int SUCCESS = 3;

    public  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private int index = 1;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ContextUtilts.getInstance().setmContext(this);
        //退至后台重新点击图标，不重启app
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }

        if (Hawk.contains("homeGray")) {
            int homeGray = Hawk.get("homeGray");
            if (homeGray == 1) {
                /*
                 *  APP整体改为灰色
                 */
                Paint mPaint = new Paint();
                ColorMatrix cm = new ColorMatrix();
                cm.setSaturation(0);
                mPaint.setColorFilter(new ColorMatrixColorFilter(cm));
                getWindow().getDecorView().setLayerType(View.LAYER_TYPE_HARDWARE, mPaint);
            }
        }


        setContentView(getContentView());

        mImmersionBar = ImmersionBar.with(this);
        setImmersionBar(mImmersionBar);

        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);

        mPresenter = initBaseIViewPresenter();
        //获取屏幕高度
        Point size = new Point();
        this.getWindowManager().getDefaultDisplay().getSize(size);
        screenHeight = size.x;
        keyHeight = screenHeight / 3;

        init();
        setListener();
        getLifecycle().addObserver(new MyObserver());

    }

    /**
     * 显示加载动画
     */
    protected void showLoading() {
        mBuilder = new LoadingDialog.Builder(this, true);
        mBuilder.setCanceledOnTouchOutside(false);
        mBuilder.setCancelable(true);
        mBuilder.show();
    }

    public void showSimpleLoading(String title) {
        builder = new LoadingDialog.Builder(this);
        builder.setCanceledOnTouchOutside(false);
        builder.setTitle(title);
        builder.setCancelable(true);
        builder.show();
    }

    /**
     * 显示加载动画
     *
     * @param title 加载提示
     */
    protected void showLoading(String title) {
        mBuilder = new LoadingDialog.Builder(this);
        mBuilder.setTitle(title);
        mBuilder.setCanceledOnTouchOutside(false);
        mBuilder.setCancelable(true);
        mBuilder.show();
    }

    /**
     * 显示加载动画
     *
     * @param percent 加载进度
     */
    protected void showLoading(int percent) {
        mBuilder = new LoadingDialog.Builder(this);
        mBuilder.setProgress(percent);
        mBuilder.setCanceledOnTouchOutside(false);
        mBuilder.setCancelable(true);
        mBuilder.show();
    }

    /**
     * 显示加载动画
     *
     * @param title   加载提示
     * @param percent 加载进度
     */
    protected void showLoading(String title, int percent) {
        mBuilder = new LoadingDialog.Builder(this);
        mBuilder.setTitle(title);
        mBuilder.setProgress(percent);
        mBuilder.setCanceledOnTouchOutside(false);
        mBuilder.setCancelable(true);
        mBuilder.show();
    }

    private LoadingDialog.Builder builder;

    public void showSimpleLoading() {
        builder = new LoadingDialog.Builder(this);
        builder.setCanceledOnTouchOutside(false);
        builder.setCancelable(true);
        builder.getmDialog().setOnDismissListener(dialog -> {

        });
        builder.show();
    }

    /**
     * 隐藏加载动画
     */
    protected void dismissLoading() {
        if (mBuilder != null) {
            mBuilder.dismiss();
        }
        if (builder != null) {
            builder.dismiss();
        }
    }

    protected void dismisPD(){
        if(pd!=null){
            pd.dismiss();
        }
    }

    /**
     * 隐藏软键盘
     */
    public void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);

    }

    public void showKeyboard(View view) {
        if (view != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (im != null) {
                view.requestFocus();
                im.showSoftInput(view, 0);
            }
        }
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token windowToken
     */
    public void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (im != null) {
                im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 点击空白区域隐藏键盘.
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent me) {
        //把操作放在用户点击的时候
        if (me.getAction() == MotionEvent.ACTION_DOWN) {
            //得到当前页面的焦点,ps:有输入框的页面焦点一般会被输入框占据
            View v = getCurrentFocus();
            //判断用户点击的是否是输入框以外的区域
            if (isShouldHideKeyboard(v, me)) {
                //收起键盘
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(me);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        //判断得到的焦点控件是否包含EditText
        if ((v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            //得到输入框在屏幕中上下左右的位置
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            return !(event.getX() > left) || !(event.getX() < right)
                    || !(event.getY() > top) || !(event.getY() < bottom);
        }
        // 如果焦点不是EditText则忽略
        return false;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detachView();
            mPresenter = null;
        }

        if (mBuilder != null) {
            mBuilder.dismiss();
        }
    }

    /**
     * 提示
     *
     * @param msg 提示信息
     */
    protected void showToast(final String msg) {
        ToastUtils.showToast(this,msg);
    }

    /**
     * 展示Toast
     *
     * @param msg
     */
    public void showToast(String msg, int type) {
        ToastUtils.showToast(this,msg);
    }


    /**
     * 设置布局
     */
    protected abstract int getContentView();

    /**
     * 配置状态栏
     */
    protected abstract void setImmersionBar(ImmersionBar mImmersionBar);

    /**
     * mPresenter
     */
    protected abstract BaseIViewPresenter initBaseIViewPresenter();

    /**
     * 初始化布局
     */
    protected abstract void init();

    /**
     * 设置监听
     */
    protected abstract void setListener();

    private static List<InputListener> inputListeners;
    public int keyHeight = 0;


    public interface InputListener {

        void showkeyboard();//软键盘弹起

        void hideKeyboard(); //软键盘关闭

    }

    public void addInputListener(InputListener inputListener) {
        if (inputListeners == null) {
            synchronized (this) {
                if (inputListeners == null) {
                    inputListeners = new ArrayList<>();
                }
            }
        }
        inputListeners.add(inputListener);
    }

    public void removeInputListener(InputListener inputListener) {
        if (inputListener != null) {
            inputListeners.remove(inputListener);
        }
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right,
                               int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
            //软键盘弹起
            for (InputListener inputListener : inputListeners) {
                inputListener.showkeyboard();
            }
        } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
            //软键盘关闭
            for (InputListener inputListener : inputListeners) {
                inputListener.hideKeyboard();
            }
        }
    }


    /**
     * 加载错误
     *
     * @param message
     */
    public void errorLoad(String message, LoadingLayout mLoading) {
        mLoading.setErrorText(message);
        mLoading.setReloadButtonText("点击重试");
        mLoading.setErrorImage(R.drawable.error_content);
        mLoading.setStatus(LoadingLayout.Error);
    }


    public void emptyLoad(LoadingLayout mLoading) {
        mLoading.setEmptyText("暂无内容");
        mLoading.setReloadButtonText("点击重试");
        mLoading.setEmptyImage(R.drawable.empty_comment);
        mLoading.setStatus(LoadingLayout.Empty);
    }

    public void setPro(int pre) {
        if (pd != null) {
            pd.setProgress(pre);
        }
    }

    /**
     * 进度条
     */
    private ProgressDialog pd;

    /**
     * 上传进度条
     */
    public void showHorizontalSimpleLoading(final String httpTag) {
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("上传中……");
        pd.setProgress(0);
        pd.setCancelable(false);
        pd.setCanceledOnTouchOutside(false);
        pd.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                pd.dismiss();
            }
        });
        pd.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
            }
        });
        pd.show();
    }


    /**
     * 删除webview隐藏接口
     *
     * @param webview
     */
    public void removeWebViewJI(WebView webview) {
        if (webview != null) {
            webview.removeJavascriptInterface("searchBoxJavaBridge_");
            webview.removeJavascriptInterface("accessibility");
            webview.removeJavascriptInterface("accessibilityTraversal");
        }
    }

    /**
     * 设置默认样式
     */
    public void setDefaultImmerBar() {
        mImmersionBar.fitsSystemWindows(true)
                .keyboardEnable(true)
                .statusBarDarkFont(true, 0.2f)
                .statusBarColor(R.color.white).init();
    }

}
